import React, { useContext, useEffect, useState } from 'react';
import {
  DatePicker,
  Empty,
  Grid,
  Input,
  Modal,
  Skeleton,
} from '@arco-design/web-react';
import useLocale from '@/utils/useLocale';
import locale from './locale';
import styles from './style//index.module.less';
import { ReplyList } from '@/api/modules/violation';
import { GlobalContext } from '@/context';
import { IconSearch } from '@arco-design/web-react/icon';
import Files from '@/assets/icon_files.svg';

import debounce from 'lodash/debounce';
import { usedownloadDoc } from '@/utils/useDownload';
import { GlobalState } from '@/store';
import { useSelector } from 'react-redux';
import cs from 'classnames';
import dayjs from 'dayjs';
import ModalTitle from '@/components/ModalTitle';
function SupportingCreate({
  visible,
  onVisible,
  refNumber,
}: {
  visible: boolean;
  refNumber: string;
  onVisible: (status: boolean) => void;
}) {
  const { rtl, lang } = useContext(GlobalContext);
  const t = useLocale(locale);
  const [listData, setListData] = useState([]);
  const [showListData, setShowListData] = useState([]);
  const [loading, setLoading] = useState<boolean>(false);

  const onCancel = () => {
    onVisible(false);
  };

  const [q, setQ] = useState('');
  const [date, setDae] = useState({ start: 0, end: 0 });
  const handleSearch = debounce((e) => {
    setQ(e);
  }, 300);
  const handleSearchDate = debounce((e) => {
    let start = 0;
    let end = 0;
    if (e) {
      start = dayjs(e[0]).unix();
      end = dayjs(e[1]).unix();
    }
    setDae(() => ({
      start,
      end,
    }));
  }, 300);

  const fetchData = () => {
    setLoading(true);
    ReplyList({ refNumber: refNumber, q: q })
      .then((res) => {
        const data = res.data;
        const filteredData = [];
        const length = data.length;
        for (let i = 0; i < length; i++) {
          const obj = data[i];
          //查询filteredData存在这个id就跳过
          const hashData = filteredData.findIndex((arr) =>
            arr.some((a) => a.id === obj.id)
          );
          if (hashData !== -1) {
            continue;
          }
          const matchingObj = data.find((item) => item.id === obj.replyTo);
          if (matchingObj) {
            filteredData.push([matchingObj, obj]);
          } else {
            filteredData.push([obj]);
          }
        }
        setListData(filteredData);
        setLoading(false);
      })
      .catch(() => {
        setLoading(false);
      });
  };

  useEffect(() => {
    if (listData.length > 0) {
      const list = listData.filter((arr) =>
        arr.some((b) => {
          const second = dayjs(
            dayjs(b.createdAt && b.createdAt).format('YYYY-MM-DD')
          ).unix();
          const isTime =
            date.end === 0 && date.start === 0
              ? true
              : second <= date.end && second >= date.start;

          return (
            b.content.toLowerCase().includes(q.trim().toLowerCase()) && isTime
          );
        })
      );
      console.log(list);
      setShowListData(list);
    }
  }, [listData, q, date]);

  useEffect(() => {
    if (visible) {
      setQ('');
      setDae(() => ({
        start: 0,
        end: 0,
      }));
      fetchData();
      return;
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visible]);
  const actions = useSelector((state: GlobalState) => state.actions);

  return (
    <div>
      <Modal
        title={<ModalTitle title={t['commmitsHistory.title']} />}
        style={{ width: '870px' }}
        visible={visible}
        onCancel={() => onCancel()}
        maskClosable={false}
        unmountOnExit={true}
        footer={null}
        className={cs(styles['history'], rtl ? 'rtl' : '')}
      >
        <div className={styles['history-search1']}>
          <Input
            style={{ width: 288 }}
            suffix={<IconSearch />}
            allowClear
            placeholder={t['commmitsHistory.search']}
            onChange={handleSearch}
          />
          <div className={styles['history-search1-date']}>
            <DatePicker.RangePicker
              onChange={handleSearchDate}
              allowClear
              style={{ width: 288 }}
              format="YYYY-MM-DD"
              disabledDate={(date) => dayjs(date).isAfter(dayjs())}
            />
          </div>
        </div>

        <Skeleton
          loading={loading}
          style={{ width: '90%', margin: '20px auto' }}
          text={{ rows: 7 }}
          animation
        >
          {showListData.length === 0 ? (
            <div className={styles['history-empty']}>
              <Empty description={t['empty.noData']} />
            </div>
          ) : (
            <div className={styles['history-scroll']}>
              {showListData.map((item, index) => (
                <div className={styles['item']} key={index}>
                  {item.map((subItem, subIndex) => (
                    <div key={subIndex}>
                      {subItem.source === 'INT' ? (
                        <>
                          {/* commit */}
                          <div className={styles['item-header']}>
                            <div className={styles['name']}>
                              {t['commmitsHistory.RepliedBy']}：
                              <span className={styles['text']}>
                                {subItem.createdBy}
                              </span>
                            </div>
                            <div className={styles['time']}>
                              {t['commmitsHistory.Updated']} {subItem.createdAt}
                            </div>
                          </div>
                          <div className={styles['item-commit']}>
                            <div className={styles['item-commit-header']}>
                              <div className={styles['name']}>
                                {subItem.createdBy}{' '}
                                {t['commmitsHistory.commented']}:
                              </div>
                              <div className={styles['time']}>
                                {subItem.createdAt}
                              </div>
                            </div>
                            <div
                              className={cs(
                                styles['item-commit-content'],
                                lang === 'en-US'
                                  ? ''
                                  : styles['item-commit-content-rtl']
                              )}
                            >
                              {subItem.content}
                            </div>
                          </div>
                        </>
                      ) : (
                        <>
                          {/* replied */}
                          <div className={styles['item-hr']}></div>
                          <div className={styles['item-commit']}>
                            <div className={styles['item-commit-header']}>
                              <div className={styles['name']}>
                                {subItem.createdBy}{' '}
                                {t['commmitsHistory.replied']}：
                              </div>
                              <div className={styles['time']}>
                                {subItem.createdAt}
                              </div>
                            </div>
                            <div
                              className={cs(
                                styles['item-commit-content'],
                                lang === 'en-US'
                                  ? ''
                                  : styles['item-commit-content-rtl']
                              )}
                            >
                              {subItem.content}
                            </div>
                          </div>

                          {/* attachments */}
                          {subItem.attachment?.length > 0 ? (
                            <div className={styles['item-hr']}></div>
                          ) : (
                            ''
                          )}
                          <div className={styles['item-files']}>
                            {subItem.attachment?.map((file) => (
                              <div
                                className={styles['file']}
                                key={file}
                                onClick={() => {
                                  if (
                                    actions.includes(
                                      'violation.detail.file/link'
                                    )
                                  ) {
                                    usedownloadDoc(file);
                                  }
                                }}
                              >
                                <Files className={styles['icon']} />
                                <span
                                  className={cs(styles['span'], 'ellipsis')}
                                >
                                  {file}
                                </span>
                              </div>
                            ))}
                          </div>
                        </>
                      )}
                    </div>
                  ))}
                </div>
              ))}
            </div>
          )}
        </Skeleton>
      </Modal>
    </div>
  );
}

export default SupportingCreate;
